﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NewLife.Redis.Core;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;


namespace NbMeterServices
{
    public static class ServiceCollectionExtensions
    {
        public static IServiceCollection AddSqlSugarServices(this IServiceCollection services)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); //默认读取：当前运行目录
            IConfigurationRoot configuration = builder.Build();

            services.AddTransient<ISqlSugarClient>(provider =>
            {
                SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
                {
                    ConnectionString = configuration["DBConnection:ConnectionString"],
                    DbType = SqlSugar.DbType.SqlServer,
                    IsAutoCloseConnection = true,
                });
                return sqlSugar;                
            });

            IdGeneratorOptions? opitons = new IdGeneratorOptions();
            opitons.WorkerId = ushort.Parse(configuration["SnowId:WorkerId"]);
            opitons.WorkerIdBitLength = byte.Parse(configuration["SnowId:WorkerIdBitLength"]);
            opitons.SeqBitLength = byte.Parse(configuration["SnowId:SeqBitLength"]);
            // 雪花Id
            YitIdHelper.SetIdGenerator(opitons);


            var data = configuration.GetSection("NB:ErrorCode");
            Common.LstEventItem = data.Get<List<NbEventItem>>();
            
            Common.Service = services.BuildServiceProvider();
            // 注册其他服务
            return services;
        }
    }
}
